﻿using CuaHangLego.Bussiness.Parser;
using CuaHangLego.Model;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CuaHangLego.DataAccess
{
    public class ChuDeDA : DABase, IDA<ChuDe>
    {

        public static ChuDeDA Instance = new ChuDeDA();

        public int Insert(ChuDe item)
        {
            SqlCommand sql = new SqlCommand();
            sql.CommandText = string.Format("INSERT INTO CHUDE ({0},{1}) VALUES('{2}',N'{3}'); SELECT CAST(scope_identity() AS int);",
                "Ten", "MoTa",
                item.Ten, item.MoTa);
            this.OpenDB();
            int rs = int.Parse(ExecuteQuerySingleValue(sql).ToString());
            this.CloseDB();
            return rs;
        }

        public bool Update(ChuDe item)
        {
            throw new NotImplementedException();
        }

        public bool Delete(ChuDe item)
        {
            SqlCommand sql = new SqlCommand();
            sql.CommandText = string.Format("DELETE FROM CHUDE WHERE {0}={1}", "ID", item.MaSo);
            OpenDB();
            int rs = int.Parse(ExecuteQuery(sql).ToString());
            CloseDB();
            return rs > 0;
        }

        public IList<ChuDe> GetAll()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = string.Format("SELECT * FROM CHUDE");
            cmd.CommandType = System.Data.CommandType.Text;
            OpenDB();
            SqlDataReader reader = ExecuteQueryReader(cmd);
            IList<ChuDe> list = new List<ChuDe>();
            while (reader.Read())
            {
                list.Add(ChuDeParser.Parse(reader));
            }
            CloseDB();
            return list;
        }

        public ChuDe GetByID(int ID)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = string.Format("SELECT * FROM CHUDE WHERE {0}={1}", "ID", ID);
            cmd.CommandType = System.Data.CommandType.Text;
            OpenDB();
            SqlDataReader reader = ExecuteQueryReader(cmd);
            ChuDe cd = new ChuDe();
            while (reader.Read())
            {
                cd = ChuDeParser.Parse(reader);
                break;
            }
            CloseDB();
            return cd;
        }
    }
}
